package com.xyy.saas.payment.job.reconciliation;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.enums.ReconciliationType;
import com.xyy.saas.payment.pojo.dto.ReconcileContext;
import com.xyy.saas.payment.service.reconciliation.ReconciliationExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wangzeqi
 */
@Slf4j
@ElasticJobConf(name = "ReconciliationJob", cron = "0 30 23 * * ?")
public class ReconciliationJob implements SimpleJob {

    private final ReconciliationExecutor executor;

    @Value("#{'${reconciliation.active-strategies:TRADE_DETAIL,FUND_ACCOUNT,JD_TRADE_DETAIL}'.split(',')}")
    private List<String> strategyNames;


    public ReconciliationJob(ReconciliationExecutor executor) {
        this.executor = executor;
    }

    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("ReconciliationJob started...shardingContext = {}", JSON.toJSONString(shardingContext));

        LocalDateTime endTime = LocalDate.now().atStartOfDay();
        ReconcileContext context = new ReconcileContext()
                .setBeginTime(endTime.minusDays(1))
                .setEndTime(endTime);


        List<ReconciliationType> activeStrategies = strategyNames.stream()
                .map(ReconciliationType::getByName)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        try {
            executor.execute(activeStrategies, context);
        } catch (Exception e) {
            log.error("ReconciliationJob execute error", e);
        }
    }

}
